<?php

namespace App\Http\Controllers\Saas;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Model\Agent;
use App\Model\Business;
use App\Model\Device;
use App\Model\UserBlack;
use App\Model\UserCashLog;
use App\User;
use App\Utils\Result;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $type = $request->input('type');
        $mobile = trim($request->input('mobile'));
        $disabled = $request->input('is_disabled');
        $autoCash= $request->input('auto_cash');
        $white = $request->input('white');
        $gongan = $request->input('gongan');
        $agentId =$request->input('agent_id');
        $isRemark = $request->input('is_remark');
        $device_count = $request->input('device_count');
        $query = User::query();
        $query->when($keyword, function($q) use ($keyword) {
            $q->where('nickname', $keyword);
        });
        if($autoCash != ''){
            $query->where('auto_cash', $autoCash);
        }
        if($disabled != ''){
            $query->where('is_disabled', $disabled);
        }
        if($gongan != ''){
            $query->where('gongan', $gongan);
        }
        if($white != ''){
            $query->where('white', $white);
        }
        $query->when($mobile, function($q) use ($mobile) {
            $q->where('mobile','like','%'. $mobile.'%');
        });
        $query->when($type, function($q) use ($type) {
//            $q->where('type', $type);
        });
        if($type == 'tenant'){
            $data = $query->with(['contract' => function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
            }, 'contract.house', 'tenant', 'bank'])
                ->orderByDesc('id')
                ->paginate($perPage, ['*'], 'page', $page);

        }else{
            if ($agentId != '') {
                $query->whereHas('business', function ($q) use ($agentId) {
                    $q->where('agent_id',end($agentId));
                });
            }
            if ($isRemark == 1) {
                $query->whereHas('business', function ($q) use ($agentId) {
                    $q->whereNotNull('remark');
                });
            }
            if($isRemark == 2){
                $query->whereHas('business', function ($q) use ($agentId) {
                    $q->whereNull('remark');
                });
            }
            // 使用whereHas来添加基于Device关联的查询条件
            if ($device_count > 0) {
                $query->whereHas('business.devices', function ($query) use ($device_count) {
                    $query
//                        ->whereNull('deleted_at')
                        ->select(DB::raw('count(*) as device_count'))
                        ->groupBy('business_id')
                        ->having('device_count', '>=', $device_count);
                });
            }
            $data = $query->with('business', 'bank','business.house','cashLog','recentCashLogs','business.order')
                ->orderByDesc('id')
                ->paginate($perPage, ['*'], 'page', $page);
            foreach($data as &$v){
                $recentCashLogs =$v->recentCashLogs->where('cash_amt', '>', 0); // 假设只有大于0的fee才计入总和
                $v->recent_transaction_count =$recentCashLogs->count();
                $v->recent_fee_total =$recentCashLogs->sum('cash_amt');
                $busId = $v->business->id;
                if($v->business->agent_id){
                    $v->agent_id =$v->business->agent_id;
                    $agent = Agent::query()->where('id',$v->business->agent_id)->first(['name','type']);
                    $v->agent_name = $agent->name;
                    $v->agent_type = $agent->type;
                }else{
                    $v->agent_id = 0;
                    $v->agent_type = 0;
                    $v->agent_name ='暂无';
                }
                $v->device_count = Device::query()->where('business_id',$busId)->count();
            }
        }
        return Result::success(new PaginationCollection($data));
    }

    public function cashLog(Request $request)
    {
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);
        $keyword = $request->input('keyword');
        $status = $request->input('status');
        $start = $request->input('start');
        $end = $request->input('end');

        $query = UserCashLog::query();
        $query->when($keyword, function($q) use ($keyword) {
            $q->whereHas('user', function($q) use ($keyword) {
                $q->where('mobile', $keyword)->orWhere('nickname', $keyword);
            });
        });
        if ($status) {
            $query->where('status', $status);
        }

        if($start){
            $query->where('created_at','>=', $start);
        }

        if($end){
            $query->where('created_at','<=', $end);
        }

        $data = $query->with(['user','user.bank'])
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);
        $time = date('Y-m-d');
        foreach($data  as &$v){
            $v->count = UserCashLog::query()->where('user_id',$v->user_id)
                ->where('created_at','>=',$time)
                ->count();
        }
        return Result::success(new PaginationCollection($data));
    }

    /**修改经销商
     * @param $id
     * @param Request $request
     * @return void
     */
    public function updateAgent($id,Request $request){
        $agentId = $request->input('agent_id');
        $remark = $request->input('remark',null);
        $month_amount = $request->input('month_amount','200');
        $month_limit = $request->input('month_limit',305);
        $device_time = $request->input('device_time');
        $service = $request->input('service');
        $max_speed = $request->input('max_speed');
        $show_speed = $request->input('show_speed');
        $query = User::query();
        $user = $query->where('id',$id)->with('business')->first();
        $user->business->agent_id = $agentId;
        $user->business->remark = $remark;
        $user->business->service = $service;
        $user->business->max_speed = $max_speed;
        $user->business->show_speed =$show_speed;
        if($device_time){
            $user->business->device_time = $device_time;
        }else{
            $user->business->device_time = null;
        }
        $user->business->save();
        $user->month_amount = $month_amount;
        if($month_amount){
            Device::query()->where('business_id',$user->business->id)
                ->update(['business_amount'=>$month_amount]);
        }
        if($month_limit){
            Device::query()->where('business_id',$user->business->id)
                ->update(['month_limit'=>$month_limit]);
        }
        $user->save();
        return Result::success();
    }



    /**修改异常信息
     * @param $id
     * @param Request $request
     * @return void
     */
    public function updateDraw($id,Request $request){
        $is_draw = $request->input('is_draw');
        $draw_fee = $request->input('draw_fee',0);
        $draw_max = $request->input('draw_max',0);
        $query = User::query();
        $user = $query->where('id',$id)->with('business')->first();
        $user->business->is_draw = $is_draw;
        $user->business->draw_fee = $draw_fee;
        $user->business->draw_max = $draw_max;
        $user->business->save();
        return Result::success();
    }

    public function remarkBus(Request $request){
        $busId = $request->input('bus_id');
        $remark = $request->input('remark');
        $business = Business::query()->find($busId);
        if(!$remark){
            $remark = null;
        }
        if($business){
            $business->remark = $remark;
            $business->save();
        }
    }


    public function changeCash(Request $request){
        $id = $request->input('id');
        $is_disabled = $request->input('auto_cash');
        $user = User::query()->where('id',$id)->first();
        $user->auto_cash = $is_disabled;
        $user->save();
        return Result::success();
    }

    public function editDisabled(Request $request){
        $id = $request->input('id');
        $is_disabled = $request->input('is_disabled');
        $user = User::query()->where('id',$id)->first();
        $user->is_disabled = $is_disabled;
        $user->save();
        if(!$user->bank){
            return Result::error(500,'用户尚未绑卡');
        }
        $card = $user->bank->cert_id;
        if($user->is_disabled == 1){
            $check = UserBlack::query()->where('card_id',$card)->first();
            if(empty($check)){
                $save['card_id'] =  $card;
                $save['card_name'] = $user->bank->card_name;
                $save['user_id'] = $id;
                $save['mobile'] = $user->mobile;
                UserBlack::create($save);
            }
        }else{
            UserBlack::query()->where('card_id',$card)->delete();
        }
        return Result::success();
    }
    public function editGongan(Request $request){
        $id = $request->input('id');
        $gongan = $request->input('gongan');
        $user = User::query()->where('id',$id)->first();
        $user->gongan = $gongan;
        $user->save();
        return Result::success();
    }

    public function editWhite(Request $request){
        $id = $request->input('id');
        $white = $request->input('white');
        $user = User::query()->where('id',$id)->first();
        $user->white = $white;
        $user->save();
        return Result::success();
    }

    public function delBlack($id){
        UserBlack::query()->where('id',$id)->delete();
        return Result::success();
    }

    public function blackList(Request $request){
        $query = UserBlack::query();
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 10);
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $query->when($mobile, function($q) use ($mobile) {
            $q->where('mobile', 'like', "%{$mobile}%");
        });
        $query->when($name, function($q) use ($name) {
            $q->where('card_name', 'like', "%{$name}%");
        });
        $data = $query->latest()->paginate($pageSize, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }



}
